import styled from 'styled-components';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import { Input, Button as AntdButton, Tree, Collapse, Modal, Drawer } from 'antd';
import { PlusOutlined, TableOutlined, SubnodeOutlined, SettingOutlined, DatabaseOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { CollapseProps } from 'antd';

import { FlowProject, MetaDataDomain, metaDataGetMetaDataObjects, metaDataGetMetaDatas, metaDataSaveDomain } from '../../../../services';
import { flowGetProjects, flowGetProjectTags } from '../../../../services/flow';
import { FlowProjectTable, ProjectEditor } from '.';
import { dsFind, getProjectTypeLable, Project } from '@/services/local';
import { PROJECT_CLASS_IDENTIFIER } from '@/services/constants';

const { Search } = Input;

export interface ProjectCategoryTreeProps {
    style?: CSSProperties;
    onProjectSelected: (projectIdentifier: string | null, projectType: string) => Promise<void>;
    version: number;
}

export const ProjectCategoryTree: React.FC<ProjectCategoryTreeProps> = (props) => {

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [domainMgrOpen, setDomainMgrOpen] = useState<boolean>(false);

    const [filter, setFilter] = useState<string>('');

    const [projects, setProjects] = useState<Array<Project>>([]);

    const [activeProject, setActiveProject] = useState<string | null>(null);

    const [activeProjectType, setActiveProjectType] = useState<string | null>(null);


    const refresh = async () => {
        try {
            let { data, total } = await dsFind(0, PROJECT_CLASS_IDENTIFIER, {});
            //
            setProjects(data);
        } catch (error) {
            console.error(error);
        }
    };
    useEffect(() => {
        refresh();
    }, [props.version]);

    useEffect(() => {
        if (projects && projects.length > 0) {
            //
            if (activeProject === null) {
                setActiveProject(projects[0].identifier);
                setActiveProjectType(projects[0].project_type);
            } else {
                //判断是否存在
                let exist = false;
                for (let i = 0; i < projects.length; i++) {
                    if (activeProject === projects[i].identifier) {
                        exist = true;
                        break;
                    }
                }
                if (!exist && activeProject !== null) {
                    setActiveProject(null);
                    setActiveProjectType(null);
                }
            }
        } else {
            setActiveProject(null);
            setActiveProjectType(null);
        }
    }, [projects]);

    useEffect(() => {
        props.onProjectSelected && props.onProjectSelected(activeProject, activeProjectType);
    }, [activeProject, activeProjectType]);

    return (
        <Container style={props.style}>
            <Header>
                <AddButton>
                    <AntdButton
                        icon={<SubnodeOutlined />}
                        onClick={async () => {
                            setDomainMgrOpen(true);
                        }}
                    ></AntdButton>
                </AddButton>
                <Search
                    style={{
                        flex: 1
                    }}
                    styles={{}}
                    placeholder="Filter"
                    allowClear={true}
                    onChange={(event) => {
                        setFilter(event.target.value);
                    }} onSearch={(value) => {
                        setFilter(value);
                    }} />
                <AddButton>
                    <AntdButton
                        icon={<PlusOutlined />}
                        onClick={async () => {
                            setIsModalOpen(true);
                        }}
                    ></AntdButton>
                </AddButton>
            </Header>
            <CollapseContainer>
                <Collapse
                    accordion={true}
                    bordered={false}
                    activeKey={[activeProject]}
                    onChange={async (keys) => {
                        console.log(keys);
                        if (keys && keys.length > 0) {
                            setActiveProject(keys[0]);
                            setActiveProjectType(projects.filter(item => item.identifier === keys[0])[0].project_type);
                        } else {
                            setActiveProject(null);
                            setActiveProjectType(null);
                        }
                    }}
                    expandIconPosition={"start"}
                    destroyInactivePanel={false}
                    items={projects.map((project, index) => {
                        return {
                            key: project.identifier,
                            label: `[${getProjectTypeLable(project.project_type)}]${project.title}`,
                            children: <ProjectTree key={index}
                                filter={filter}
                                onSelect={async (key: string | null, node: CategoryTreeNode | null) => {
                                }} project={project}
                            ></ProjectTree>,
                            styles: {
                                body: {
                                    padding: '0'
                                }
                            }
                        }
                    })}
                />
            </CollapseContainer>
            <Modal
                styles={{
                    content: {
                        minWidth: '600px',
                        minHeight: '400px'
                    }
                }}
                title="创建工程"
                footer={false}
                destroyOnClose={true}
                open={isModalOpen}
                onOk={() => {
                    setIsModalOpen(false);
                }} onCancel={() => {
                    setIsModalOpen(false);
                }}>
                <ProjectEditor onFinish={async () => {
                    //
                    await refresh();
                    setIsModalOpen(false);
                }}></ProjectEditor>
            </Modal>
            <Drawer
                title="工程管理"
                onClose={async () => {
                    //刷新
                    await refresh();
                    setDomainMgrOpen(false);
                }}
                width={'calc(100% - 270px)'}
                destroyOnClose={true}
                open={domainMgrOpen}>
                <FlowProjectTable></FlowProjectTable>
            </Drawer>
        </Container>
    );
}



interface CategoryTreeNode {
    title: string;
    key: string;
    icon?: any;
    isLeaf?: boolean;
    children: CategoryTreeNode[];
}

const updateTreeData = (list: CategoryTreeNode[], key: React.Key, children: CategoryTreeNode[]): CategoryTreeNode[] =>
    list.map((node) => {
        if (node.key === key) {
            return {
                ...node,
                children,
            };
        }
        if (node.children) {
            return {
                ...node,
                children: updateTreeData(node.children, key, children),
            };
        }
        return node;
    });

export interface ProjectTreeProps {
    style?: CSSProperties;
    project: Project;
    filter: string;
    onSelect: (key: string | null, node: CategoryTreeNode | null) => Promise<void>;
}

const ProjectTree: React.FC<ProjectTreeProps> = (props) => {

    const [treeData, setTreeData] = useState<Array<CategoryTreeNode>>([]);

    const navigate = useNavigate();

    useEffect(() => {

    }, [props.project]);

    return (
        <TreeContainer style={props.style}>
        </TreeContainer>
    );
}


const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
`;

const Header = styled.div`
    height: 45px;
    width: 100%;
    padding: 0 0px;
    display: flex;
    background-color: #EFEFEF;
    align-items: center;
    justify-content: space-between;
`;

const AddButton = styled.div`
    width: 34px;
    display: flex;
    align-items: center;
    justify-content: center;
`;

const CollapseContainer = styled.div`
    flex: 1;
    width: 100%;
    overflow-y: auto;
    overflow-x: auto;
`;

const TreeContainer = styled.div`
    flex: 1;
    width: 100%;
`;